package com.kangjia.holder;

import java.util.HashMap;
import java.util.Map;

/**
 * 线程变量存储
 * 
 * @author sunshulin
 * 
 */
public class VariableThreadLocal {

	private static ThreadLocal<VariableThreadLocal> variable = new ThreadLocal<>();

	private Map<String, Object> params = new HashMap<>();

	public static <T> T get(String key) {
		VariableThreadLocal variableThreadLocal = variable.get();
		if (variableThreadLocal == null) {
			return null;
		}
		return variableThreadLocal.getByKey(key);
	}

	public static <T> void set(String key, T value) {
		VariableThreadLocal variableThreadLocal = variable.get();
		if (variableThreadLocal == null) {
			variableThreadLocal = new VariableThreadLocal();
			variable.set(variableThreadLocal);
		}
		variableThreadLocal.put(key, value);
	}

	@SuppressWarnings("unchecked")
	private <T> T getByKey(String key) {
		return (T) params.get(key);
	}

	private <T> void put(String key, T value) {
		params.put(key, value);
	}
}
